<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          type="text"
          style="margin-bottom: 10px"
          size="small"
          prefix-icon="el-icon-search"
          placeholder="输入员工姓名全员搜索"
          @input="searchKeyword"
        />
        <!-- 树形结构 -->
        <el-tree
          ref="tree"
          :data="treeList"
          :props="defaultProps"
          default-expand-all
          highlight-current
          node-key="id"
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row type="flex" class="opeate-tools" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column
            label="头像"
            prop="staffPhoto"
            align="center"
          >
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            label="手机号"
            prop="mobile"
            sortable
          />
          <el-table-column
            label="工号"
            prop="workNumber"
            sortable
          />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
          >
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment===1">正式员工</span>
              <span v-else-if="row.formOfEmployment===2">非正式员工</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            prop="departmentName"
          />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
          />
          <el-table-column
            label="操作"
          >
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="getPer(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="handleDelete(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="total,prev, pager, next"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            :total="total"
            @current-change="handleChange"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog :visible.sync="showDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <!-- 权限弹窗 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="setPermission">确定 </el-button>
          <el-button size="mini" @click="showDialog=false">取消 </el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { getEmployList, exportEmployee, employeeDelete,
  getEmployeeDetail, getEnableList, setRolePermission } from '@/api/employee'
import { transListToTreeData } from '@/utils/index'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      treeList: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: null
      },
      employeeList: [],
      total: null,
      showExcelDialog: false,
      showDialog: false,
      roleList: [],
      roleIds: [],
      currentId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.treeList = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.treeList[0].id
      // 树形组件是异步渲染的 所以等待更更新完毕
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployList(this.queryParams)
      this.employeeList = rows
      this.total = total
    },
    handleChange(newpage) {
      this.queryParams.page = newpage
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    searchKeyword() {
      // 节流 在单位时间内只响应一次请求
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1 // 每次查询之前将页面从第一页显示
        this.getEmployeeList()
      }, 300)
    },
    async exportEmployee() {
      const result = await exportEmployee()
      FileSaver.saveAs(result, '员工信息表.xlsx')
      // 将二进制文件流（如Excel表格）保存为本地文件并下载到用户电脑，文件名会显示为 员工信息表.xlsx
    },
    async handleDelete(id) {
      await employeeDelete(id) // 删除后台数据 前台更新还需一定时间
      if (this.employeeList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    // 拿到角色权限     获得当前角色的权限
    async getPer(id) {
      this.roleList = await getEnableList()
      this.currentId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showDialog = true
    },
    // 分配角色的权限
    async setPermission() {
      await setRolePermission({
        id: this.currentId,
        roleIds: this.roleIds
      })
      this.$message.success('分配成功')
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  display: flex;
  background: #fff;
  .left{
    width: 280px;
    padding: 20px;
    border-right: 1px solid #edeef4;
  }
  .right{
    flex: 1;
    padding: 20px;
    .opeate-tools{
      margin: 20px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }

}

</style>
